<template>
  <!-- 录入用户名 2018/3/7 11:44 zhangQ -->
  <div>
    <Form ref="nameForm" label-position="left" :label-width="100" :model="nameForm" :rules="ruleNameForm" @submit.native.prevent>
      <FormItem label="用户名" prop="loginName">
        <Input placeholder="请输入登录用户名" class="input" size="large" style="width: 316px"
               v-model="nameForm.loginName"></Input>
      </FormItem>
      <FormItem label="">
        <div id="captcha">
          <p id="wait">正在加载验证码......</p>
        </div>
      </FormItem>

    </Form>
  </div>
</template>

<script>
  import { checkUser, getGtConf } from '@api/common/user'
  import initGeetest from '@/vendor/initGeetest'

  export default {
    name: 'input-user-name',
    data () {
      let nameForm = {
        loginName: ''
      }
      let ruleNameForm = {
        loginName: [
          { required: true, message: '用户名不能为空', trigger: 'blur' },
          {
            checkUser: checkUser,
            Vue: this,
            trigger: 'blur',
            validator (rule, value, callback) {
              let formatError = '输入非法，中文、英文、_- 4-12位'
              let noExistError = '用户名不存在'
              if (!value) {
                callback(new Error(formatError))
                return
              }
              let reg = /^[a-zA-Z0-9\u4e00-\u9fa5_-]{4,12}$/
              if (!reg.test(value)) {
                callback(new Error(formatError))
                return
              }
              this.Vue.formValicade = false
              this.checkUser({ type: 'loginName', value: value }).then((response) => {
                let resData = response.data
                if (+resData.isSuccess === 1) {
                  this.Vue.userInfo = resData
                  this.Vue.formValicade = true
                  callback()
                } else {
                  callback(new Error(noExistError))
                }
              }).catch(() => {
                callback(new Error(noExistError))
              })
            }
          }
        ]
      }
      let successGeetest = false
      let formValicade = false
      let userInfo = {}
      let datas = { nameForm, ruleNameForm, successGeetest, formValicade, userInfo }
      return datas
    },
    computed: {},
    methods: {
      /**
       * 校验用户名
       * @param name:::表单名
       * */
      checkLoginName (name) {
        this.$refs[name].validate((valid) => {
          if (valid) {
            this.formValicade = true
          } else {
            this.formValicade = false
          }
        })
      },
      /**
       * 极验证
       * @param captchaObj
       */
      gretestHandler (captchaObj) {
        captchaObj.appendTo('#captcha') // 同时插入三个input表单时，geetest_challenge, geetest_validate, geetest_seccode
        captchaObj.onReady(function () {
          $('#wait').hide()
        })
        $('#btn').click(function (e) {
          var result = captchaObj.getValidate()
          if (!result) {
            e.preventDefault()
            return alert('请完成验证')
          }
        })
        captchaObj.onSuccess(() => {
          this.successGeetest = true
          this.checkLoginName('nameForm')
        })
        // 更多接口说明请参见：http://docs.geetest.com/install/client/web-front/
      }
    },
    created () {
    },
    watch: {},
    mounted () {
      this.$watch(() => {
        return this.successGeetest && this.formValicade
      }, (newVal, oldVal) => {
        if (newVal) {
          this.$emit('next', true, this.userInfo)
        } else {
          this.$emit('next', false)
        }
      })
      getGtConf()
        .then((response) => {
          // 调用 initGeetest 进行初始化
          // 参数1：配置参数
          // 参数2：回调，回调的第一个参数验证码对象，之后可以使用它调用相应的接口
          let data = JSON.parse(response.data.data)
          initGeetest({
            // 以下 4 个配置参数为必须，不能缺少
            gt: data.gt,
            challenge: data.challenge,
            offline: !data.success, // 表示用户后台检测极验服务器是否宕机
            new_captcha: data.new_captcha, // 用于宕机时表示是新验证码的宕机
            product: 'float', // 产品形式，包括：float，popup
            width: '316px'
            // 更多配置参数说明请参见：http://docs.geetest.com/install/client/web-front/
          }, this.gretestHandler)
        })
        .catch((error) => {
          console.log(error)
        })
    },
    components: {}
  }
</script>

<style scoped>

</style>
